from django.db import models
from instance.models import DBInstance, StorageInstance
from django.utils import timezone


class BackupConfig(models.Model):
    """
    备份配置
    """
    name = models.CharField(
        default='',
        max_length=50,
        verbose_name='名称'
    )
    storage_instance = models.ForeignKey(
        StorageInstance,
        verbose_name='存储实例',
        null=True,
        on_delete=models.SET_NULL
    )
    db_instance = models.ForeignKey(
        DBInstance,
        verbose_name='DB实例',
        null=True,
        on_delete=models.SET_NULL
    )
    backup_path = models.CharField(
        default='',
        max_length=200,
        verbose_name='备份路径'
    )

    class Meta:
        verbose_name = "备份配置"
        verbose_name_plural = "备份配置 - (BackupConfig)"

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        super(BackupConfig, self).save()
        create_uid = 0
        if 'create_uid' in kwargs:
            create_uid = kwargs['create_uid']
        obj = BackupConfigRecord.objects.create(
            backup_config_id=self.id,
            storage_instance_id=self.storage_instance.id,
            db_instance_id=self.db_instance.id,
            backup_path=self.backup_path,
            create_uid=create_uid,
        )


class BackupConfigRecord(models.Model):
    """
    备份配置记录
    """
    create_uid = models.IntegerField(
        default=0,
        verbose_name='创建记录用户ID'
    )
    create_date = models.DateTimeField(
        default=timezone.now,
        verbose_name='创建时间'
    )

    backup_config_id = models.IntegerField(
        default=0,
        verbose_name='配置ID'
    )
    storage_instance_id = models.IntegerField(
        default=0,
        verbose_name='存储实例ID'
    )
    db_instance_id = models.IntegerField(
        default=0,
        verbose_name='DB实例ID'
    )
    backup_path = models.CharField(
        default='',
        max_length=200,
        verbose_name='备份路径'
    )

    class Meta:
        verbose_name = "备份配置记录"
        verbose_name_plural = "备份配置记录 - (BackupConfigRecord)"


class BackupRecord(models.Model):
    """
    备份记录
    """
    create_uid = models.IntegerField(
        default=0,
        verbose_name='创建记录用户ID'
    )
    create_date = models.DateTimeField(
        default=timezone.now,
        verbose_name='创建时间'
    )

    backup_config_id = models.IntegerField(
        default=0,
        verbose_name='配置ID'
    )
    storage_instance_id = models.IntegerField(
        default=0,
        verbose_name='存储实例ID'
    )
    db_instance_id = models.IntegerField(
        default=0,
        verbose_name='DB实例ID'
    )
    backup_filepath = models.CharField(
        default='',
        max_length=200,
        verbose_name='备份路径'
    )

    class Meta:
        verbose_name = "备份记录"
        verbose_name_plural = "备份记录 - (BackupRecord)"
